package com.test.servlet;

import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.test.database.DBManager;

public class MessageRead extends HttpServlet {
	private int REFRESH_ITEM_NUM = 5;
	private DBManager db;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
    	response.setContentType("text/html; charset=UTF-8" );
		DataOutputStream dos = new DataOutputStream(response.getOutputStream());
		db = new DBManager();
		String action = request.getParameter("action");
		String result = null;
		if("first_refresh".equals(action)) {
			result = handleFirstRefresh();
			System.out.println("result = " + result);
		} else if ("refresh".equals(action)) {
			String currentItemCountStr = request.getParameter("start");
			int currentItemCount = Integer.parseInt(currentItemCountStr);
			result = handleRefresh(currentItemCount);
		}
		dos.writeUTF(result);
		dos.flush();
		dos.close();
		//String currentItemCountStr = request.getParameter("current_item_count");
		//int currentItemCount = Integer.parseInt(currentItemCountStr);
		
    }
    
    private String handleFirstRefresh() {
		return getData(0, REFRESH_ITEM_NUM);
	}
    
    private String handleRefresh(int start) {
    	return getData(start, REFRESH_ITEM_NUM);
    }
    
    private String getData(int start, int count) {
    	String sql = "select * from " + DBManager.TABLE_NAME_MESSAGE 
				+ " order by " + DBManager.COLUMN_TIME + " desc "
				+ "limit " + start + ", " + count;
    	System.out.println("sql = " + sql);
    	ResultSet rst = db.query(sql);
    	ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    	HashMap<String, Object> map = null;
    	try {
			while(rst.next()) {
				map = new HashMap<String, Object>();
				String username = rst.getString(DBManager.COLUMN_USERNAME);
				Timestamp time = rst.getTimestamp(DBManager.COLUMN_TIME);
				String title = rst.getString(DBManager.COLUMN_TITLE);
				String content = rst.getString(DBManager.COLUMN_CONTENT);
				map.put(DBManager.COLUMN_USERNAME, username);
				map.put(DBManager.COLUMN_TIME, time);
				map.put(DBManager.COLUMN_TITLE, title);
				map.put(DBManager.COLUMN_CONTENT, content);	
				list.add(map);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	return (new Gson()).toJson(list);
    }

	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
    	doGet(request, response);
    }
}
